# -*-encoding=utf-8 -*-
# 导包
import logging
import os
import sys
import threading
import unittest, config, time
from lib import HTMLTestRunner_PY3
import threadpool
from threadpool import ThreadPool


#
# from script.test_login_params import TestLoginParams
# from script.test_login import TestLogin
# from script.test_thrid import WeatherInfo
# from utils import DataManger
# # 创建测试套件
# suite = unittest.TestSuite()
# # 将测试用例添加到测试套件
# suite.addTest(unittest.makeSuite(TestLoginParams))
# suite.addTest(unittest.makeSuite(TestLogin))
# suite.addTest(unittest.makeSuite(WeatherInfo))
# # 使用HTMLTestRunner_PY3运行测试套件，生成测试报告
# report_name = config.BASE_DIR + f"/report/lagou_edu {time.strftime('%Y%m%d %H%M%S')}.html"
# with open(report_name, mode='wb') as f:
#     # 实例化runner
#     runner = HTMLTestRunner_PY3.HTMLTestRunner(f)
#
#     # 使用runner运行测试套件
#     result = runner.run(suite)
#     # 生成报告
#     runner.generateReport(suite, result)


def loader_case(case_path, rule):
    alltestcase = unittest.defaultTestLoader.discover(case_path, pattern=rule)  # 使用defaultTestLoader加载测试用例
    return alltestcase


def gen_result(result_list):
    primary_result = result_list[0]
    print("primary_result:", primary_result)
    for i in range(1, len(result_list)):
        data = result_list[i].result
        for j in data:
            primary_result.addSuccess(j[1])
            primary_result.testsRun += 1
    return primary_result


def run_testsuite(suite):
    report_path = config.BASE_DIR + "/report/report.html"
    with open(report_path, mode='wb') as f:
        runner = HTMLTestRunner_PY3.HTMLTestRunner(f)
        runner.run(suite)


class RunAndReport:

    def __init__(self):
        self.report_path = config.BASE_DIR + "/report/report.html"
        self.f = open(self.report_path, mode='wb')
        self.runner = HTMLTestRunner_PY3.HTMLTestRunner(self.f)
        self.result_list = list()

    def run_testsuite(self, suite):
        # 运行测试套件
        result = self.runner.run(suite)
        # 将运行的结果添加到列表中（多线程执行时使用）
        self.result_list.append(result)
        # logging.info(f"每次执行一组用例后的result结果为：{result}")
        # logging.info(f"每次执行一组用例后的result.result结果为：{result.result}")

    # 生成测试报告
    def gen_report(self, all_suite):
        primary_result = self.result_list[0]
        for i in range(1, len(self.result_list)):
            data = self.result_list[i].result
            for j in data:
                # logging.info(f"查看每次循环，提取的值：{j}")
                if j[0] == 0:
                    primary_result.addSuccess(j[1])
                    primary_result.testsRun += 1
                if j[0] ==1:
                    primary_result.addFailure(j[1],sys.exc_info())
                    primary_result.testsRun += 1
                if j[0] ==2:
                    primary_result.addError(j[1],sys.exc_info())
                    primary_result.testsRun += 1
        self.runner.generateReport(all_suite, primary_result)
        return primary_result

def main():
    case_path = config.BASE_DIR + "/script"
    rule = "test_*.py"

    pool = ThreadPool(10)
    # 加载测试套件
    cases = loader_case(case_path, rule)
    # 实例化运行测试套件和生成测试报告的类
    task = RunAndReport()
    # 设置任务请求（执行测试用例run_testsuite)
    requests = threadpool.makeRequests(task.run_testsuite, cases)
    # 把请求放入线程池中，运行起来
    for req in requests:
        print("任务列表：", req)
        pool.putRequest(req)

    pool.wait()
    # 生成测试报告
    task.gen_report(cases)
    # 结束
    logging.info("用例执行结束：------------------------")

if __name__ == '__main__':
    main()
